<template>
  <view class="content">
    <login v-if="!is_login && is_show" v-on:x="no_login" v-on:plogin="to_login"></login>
    <hongbao ref="hb" v-show="hongbao" v-on:is_open="is_open_hb" v-on:no_hongbaos="no_hongbao"></hongbao>
    <!-- tabbar -->
    <footer-menu ref="footerMenu" :active="'sindex'"/>
    <!-- 顶部样式 -->
    <!-- 确认提货弹窗 -->
    <pickup_pop ref="pickUp"></pickup_pop>
    <!-- 商品弹窗 -->
    <view v-show="active == 0">
      <goods_pop ref="goodsShow" @updateGoodsShow="updateGoodsShow"></goods_pop>
    </view>
    <!-- 问卷弹窗 -->
    <question_pop></question_pop>
    <!-- 大促转盘-->
    <dacu-7 ref="dacu7" @videoSet="videoSet()"></dacu-7>
    <!-- 直播答题弹框 -->
    <live-answer-pop ref="liveAnswerPop"></live-answer-pop>
    <!-- 答题成功弹框 -->
    <yes_dati v-if="is_dati" v-on:no_dati="no_dati" :username="dati_info.username"
              :d_z_username="dati_info.dianzhang" :video_name="dati_info.video" :yao_name="dati_info.yaoqingren"
              :time="dati_info.time"></yes_dati>
    <!-- 积分弹窗 -->
    <jifen_pop v-if="jf_pop && !(showNewYear && active === 1)" v-on:downPop="downPop()"
               :wd_totalIntegral="wd_totalIntegral" :wd_total="wd_total">
    </jifen_pop>
    <!--    隐私协议-->
    <generate-privacy-protocol></generate-privacy-protocol>
    <!-- tab栏目 -->
    <!-- <ms-tabs :list="list" v-model="active" :lineAnimated="false"></ms-tabs> -->
    <index-top-tap v-if="list.length!=0" :list="list" ref="top_tap"
                   v-on:setSwiper="setSwiper"
                   :index="active"></index-top-tap>
    <!-- 切屏 -->
    <!-- 不展示新年活动页面 -->
    <swiper class="swiper" :cancelable="false" @change="swiperChange" :current="active">
      <swiper-item v-for="(item,index) in list" :key="item.id">
        <!-- 收藏列表 -->
        <collection @commentHide="footerMenuShow=true" @commentShow="footerMenuShow=false"
                    v-if="item.id==2 && active==index && isSwiperItem"
                    v-on:pgetMessageList="getMessageList"></collection>
        <!-- 推荐 -->
        <recommended ref="recommended" :class_name="item.name" :class_id="item.id"
                     v-if="item.id!=0 && item.id!=1 && item.id!=2 && index==active && isSwiperItem"></recommended>
        <!-- 视频 -->
        <video-list @setToCircle="isToCircle=true" @commentHide="footerMenuShow=true"
                    @commentShow="footerMenuShow=false" ref="videoList" v-on:setSwiper="setSwiper" :active="active"
                    :method="active==0?'get':'post'"
                    :api="active==0?'ruiVideo/index/list':active==1?'follow/followList': active == 2 ? 'collect/collectionList': ''"
                    v-on:pgetMessageList="getMessageList" :video_list_type="item.id"
                    v-if="(item.id==0 || item.id==1) && active==index && is_video_show && isSwiperItem">
        </video-list>
        <!-- 视频分享按钮 -->
        <button :style="'top:'+fenxiang_stype.top+'rpx'" v-if="item.id==12 && active==index" class="shares"
                type="default" open-type="share"></button>
      </swiper-item>
    </swiper>
    <View v-if="isShowTaskEnter" class="task-enter" :style="{top:contentTopcount+106+'px'}"
          @click="goToNewPeopleTask()">
      <image :src="`${imgBasePath}newtask/task-enter-icon.png`" class="task-enter-icon"></image>
    </View>
  </view>
</template>
<script>
import {imgBasePath, trackingHost, stateHost} from "@/common/config";

export default {
  data() {
    return {
      list: [],
      active: 0,
      show: false,
      sing_info: {},
      time: 3,
      sing_yes: "",
      info: [],
      fenxiang_stype: "",
      is_login: uni.getStorageSync("token"),
      is_show: true,
      is_dati: false,
      dati_info: {},
      hongbao: false,
      statusBarHeight: uni.getStorageSync('menuInfo').statusBarHeight,
      jifen_num: 10,
      jifen_count: 1,
      jf_pop: false,
      wd_total: 0, // 未读积分笔数
      wd_totalIntegral: 0, // 未读总积分
      is_video_show: false,
      is_fenxiang: false,
      contentTopcount: uni.getStorageSync('menuInfo').contentTopcount, //胶囊相关
      isShowTaskEnter: false,
      imgBasePath,
      footerMenuShow: true,
      isSwiperItem: true,
      isToCircle: false,
      notSwip: false,
      showGoods: false
    }
  },
  watch: {
    active: function (newValue, oleValue) {
      console.log('active', newValue, oleValue)
      this.isSwiperItem = false
      this.$nextTick(() => {
        this.isSwiperItem = true
      })
    },
    footerMenuShow: function (newValue, oleValue) {
      if (newValue) {
        this.$refs.footerMenu.show()
      } else {
        this.$refs.footerMenu.hide()
      }
    }
  },
  // 页面隐藏调用
  onHide() {
    this.utils.clearIntervalAll('videoRewardSetIntervalAll')
  },
  onShareAppMessage(res) {
    if (res.from === 'button') { // 来自页面内分享按钮
      console.log("share from btn", res);
    }
    this.is_fenxiang = true
    this.to_dianzan(this.info.id)
    // 打印分享内容
    console.log(this.info.title)
    console.log(this.info.coverUrl)
    console.log('/pages/sindex/index.html?info=' + JSON.stringify(this.info))
    //视频分享
    return {
      title: this.info.title,
      path: '/pages/sindex/index?videoId=' + this.info.id
    }
  },
  async onLoad(e) {
    this.sendYZlog(e)
    if (e.info) {
      let video = JSON.parse(e.info);
      video.requestId = '';
      video.tag = '';
      video.sceneId = '';
      video.channel = 1;
      video.hasAward = ''
      let data = {
        video: video,
        type: 301
      }
      uni.setStorageSync("to_index_video", data);
    }
  },
  async onShow() {
    if (this.is_fenxiang || this.isToCircle) {
      this.is_fenxiang = false;
      this.isToCircle = false;
      return
    }

    if (getApp().globalData.isFromTaskCenter) {
      getApp().globalData.isFromTaskCenter = false;
      this.active = 0;
    }
    let e = uni.getEnterOptionsSync()
    if (e.query.videoId) {
      let video = await this.getVideoInfo(e.query.videoId)
      let data = {
        video: video,
        type: 301
      }
      uni.setStorageSync("to_index_video", data);
    }
    this.get_art_class_list()
    this.$refs.hb.check_have_red();
    this.is_video_show = false;
    this.$nextTick(() => {
      this.is_video_show = true;
    })

    uni.hideTabBar();
    if (uni.getStorageSync("dati_json")) {
      this.is_dati = true;
      this.dati_info = uni.getStorageSync("dati_json");
      uni.setStorageSync("dati_json", false)
    }
    this.is_show = true
    this.is_login = uni.getStorageSync("token")
    this.updataapp()
    this.check_is_jf_pop();
    this.getTaskEnterLimits();
    this.$refs.dacu7.init()
    this.$refs.liveAnswerPop.getLiveInfo()
    if (uni.getStorageSync('to_index_message') === true) {
      uni.setStorageSync('to_index_message', false)
      setTimeout(() => {
        this.$refs.top_tap && this.$refs.top_tap.showMessage()
      }, 500)
    }
    this.$refs.pickUp.getPickupInfo();
  },
  methods: {
    getVideoInfo(videoId) {
      return new Promise((resolve, reject) => {
        this.$javaCircle.doRequest('get', 'vs/ruiVideo//info/' + videoId).then(res => {
          resolve(res.data.data)
        })
      })
    },
    getCurrentDate() {
      const date = new Date();
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    },

    updateGoodsShow(isShow) {
      if (this.showGoods !== isShow) {
        this.showGoods = isShow
      }
    },

    // 预知助手链接进入小程序埋点
    sendYZlog(e) {
      let is_login = uni.getStorageSync("token") || false
      if (!is_login) {
        uni.setStorageSync('isToYZ', e)
        return
      }
      if (e?.source == 'yuzhi') {
        if (e?.shareFrom == 'newYear') {
          this.$dadian('YZShowNewYear')
        }
        if (e.info) {
          let video = JSON.parse(e.info);
          this.$dadian('YZShowVideo' + video.id)
        }
      }
    },
    videoSet(type) {
      // 大转盘暂停视频
      let that = this
      setTimeout(() => {
        that.$refs.videoList && that.$refs.videoList[0]?.videoSet()
      }, 3000)
    },

    findCus() {
      return this.$request("api/red/yzkj/findCus", {method: "GET", host: stateHost})
          .then(res => {
            const {storeId} = res;
            this.storeId = storeId;
            uni.setStorageSync("storeId", storeId);
            return res;
          }).catch(() => null)
    },
    mainPageFlag(event) {
      const {unionid, openid} = uni.getStorageSync("userInfo");
      const params = {
        oid: openid,
        uid: unionid,
        sid: this.storeId,
        ts: Date.parse(new Date()) / 1000,
        event,
        page: "mainPageFlag",
      }
      this.$request("event-tracking/user", {host: trackingHost, params})
          .catch(() => {
          })
    },
    // 获取入口权限
    async getTaskEnterLimits() {
      await this.findCus();
      this.$request("marketing/user/activity/available", {
        params: {
          source: "Floating",
          activityType: "New_People_Task"
        }
      })
          .then(data => {
            this.isShowTaskEnter = data.result;
            this.mainPageFlag("impression");
          }).catch(error => {
      })
    },
    // 跳转到新人任务页
    goToNewPeopleTask() {
      this.mainPageFlag("click");
      uni.navigateTo({
        url: `/pages/newPeopleTask/index?source=4`
      });
    },
    test() {
      uni.reLaunch({
        url: '/pages/newAnswer/register?type=index'
      });
    },
    check_is_jf_pop() {
      var that = this;
      that.$javaApi.doRequest("post", "/customerkt/integral/integralNoRead", {}, 'json').then(res => {
        if (res.data.code == 0) {
          this.wd_total = res.data.data.total;
          this.wd_totalIntegral = res.data.data.totalIntegral;
          if (this.wd_total != 0 & this.wd_totalIntegral != 0) {
            this.jf_pop = true;
          }
        }
      })
    },
    downPop() {
      var that = this;
      that.$javaApi.doRequest("post", "/customerkt/integral/integralRead", {}, 'json').then(res => {
        if (res.data.code == 0) {
          this.jf_pop = false
        }
      })
    },
    no_hongbao() {
      this.hongbao = false
    },
    is_open_hb() {
      this.hongbao = true
      console.log('王帅123');
    },
    updataapp() {
      const updateManager = wx.getUpdateManager()

      updateManager.onCheckForUpdate(function (res) {
        // 请求完新版本信息的回调

      })

      updateManager.onUpdateReady(function () {
        wx.showModal({
          title: '更新提示',
          content: '新版本已经准备好，是否重启应用？',
          success(res) {
            if (res.confirm) {
              // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
              updateManager.applyUpdate()
            }
          }
        })
      })

      updateManager.onUpdateFailed(function () {
        // 新版本下载失败
      })
    },
    no_dati() {
      this.is_dati = false;
    },
    no_login() {
      this.is_show = false
    },
    async to_login() {
      this.list = [];
      let e = uni.getEnterOptionsSync()
      if (e.query.videoId) {
        let video = await this.getVideoInfo(e.query.videoId)
        let data = {
          video: video,
          type: 301
        }
        uni.setStorageSync("to_index_video", data);
      }
      this.get_art_class_list()
      uni.hideTabBar();
      this.$refs.footerMenu.getConfig()
      this.is_login = uni.getStorageSync("token")
      this.is_show = false;
      this.sendYZlog(uni.getStorageSync("isToYZ"))
      this.$refs.goodsShow.appDrainageInit()
    },
    changeSwiper(e) {
      this.swiperCurrent = e.detail.current;
    },
    swiperChange(e) {
      console.log('swiperChange', e.detail)
      this.active = e.detail.current
      this.$refs.top_tap.set(this.active)
      this.footerMenuShow = true
      this.$forceUpdate();
    },
    setSwiper(index, isClick = false) {
      this.active = index

    },
    search(info) {
      uni.navigateTo({
        url: "/pages/sindex/search?search=" + info.value
      })
    },
    input(info) {

    },
    get_art_class_list() {
      var _this = this;
      _this.$api.doRequest("get", "api/art_class_list").then(res => {
        if (res.data.data[0] && res.data.data[0].id == 16) {
          _this.list = res.data.data;
        } else {
          // 新年活动相关
          _this.list = [
            {id: 0, name: '推荐'},
            {id: 1, name: '关注'},
            {id: 2, name: '收藏'}
          ]
        }
        if (res.data.code == 401) {
          _this.login();
        }
      })
    },
    login() {
      // 获取微信code
      var _this = this;
      uni.login({
        provider: 'weixin',
        success: function (loginRes) {
          _this.check_login(loginRes.code);
        }
      })
    },
    // 检测登录
    check_login(code) {
      var _this = this;
      _this.$api.doRequest("post", 'api/wechat_user_login', {
        code: code
      }).then(res => {
        if (res.data.code == 200) {
          uni.setStorageSync("token", res.data.data.token)
          uni.setStorageSync("userInfo", res.data.data)
          if (res.data.data.is_register == 1) {
            uni.reLaunch({
              url: '/pages/newAnswer/register?type=index'
            });
          } else {
            // uni.setStorageSync("k_token", res.data.data.token)
            _this.get_art_class_list();
          }
        } else {

        }
      })
    },
    get_user_sign_info() {
      var _this = this;
      _this.$api.doRequest("get", "api/user_sign_info").then(res => {
        _this.show = res.data.data.is_sign_today == 1 ? false : true;
        _this.sing_info = res.data.data;
      })
    },
    getMessageList(item, index, data) { //获取分享id
      // this.fenxiang_stype=data
      this.info = item;
      // 获取视频是否关联商品
      this.$refs.goodsShow.getGoodsInfo(item)
    },
    to_dianzan(id) { //记录分享
      var data = {
        videoId: id,
        action: 5
      };
      var _this = this;
      _this.$NoteApi.doRequest("post", 'action/report', data, 'json').then(res => {
        console.log(res);
      })

    },
    commentHide() {
      console.log("guanbi")
    }

  }
}
</script>

<style>
page {
  width: 100%;
  height: 100%;
  /* overflow-y:scroll; */
  display: flex;
  flex-direction: column;
  -webkit-overflow-scrolling: auto;
}

.content {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #383838;
  -webkit-overflow-scrolling: auto
}

.task-enter {
  position: fixed;
  right: 40rpx;
  width: 126rpx;
  height: 126rpx;
}

.task-enter-icon {
  width: 126rpx;
  height: 126rpx;
}

.zhezhao {
  position: fixed;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  background-color: #000000;
  opacity: 0.5;
  z-index: 10;
}

.qiandao .tu {
  width: 562upx;
  height: 840upx;
  background-color: #FFFFFF;
  background: url(https://mes.renkangshangcheng.cn/appimage/qiandaotanchuang.png);
  background-repeat: no-repeat;
  background-size: 100% auto;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  border-radius: 28upx;
  z-index: 11;
}

.qiandao .x {
  width: 60upx;
  height: 60upx;
  position: fixed;
  top: 85%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: #999999;
  border: 2upx solid #FFFFFF;
  border-radius: 50%;
  z-index: 11;
  line-height: 60upx;
  text-align: center;
}

.qiandao .title {
  width: 100%;
  text-align: center;
  margin-top: 200upx;
}

.content {
  margin: 0;
  padding: 0;
}

.swiper {
  height: 100%;
  display: flex;
}

.indextop {
  font-size: 20upx;
  width: 100%;
  height: 10upx;
  /* background-image: url(https://mes.renkangshangcheng.cn/appimage/topbgm.png); */
  background-repeat: no-repeat;
  background-size: 100% 100%;
}

.indextop-title {
  width: 750upx;
  text-align: center;
  padding-top: 78upx;
  font-size: 34upx;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500;
  color: #000;
}

#indextop-search {
  width: 690upx;
  margin: 0 auto;
  margin-top: 44upx;
  opacity: 0.5;
  /* text-align: left; */
  /* height: 64upx; */
  /*


  background: #fff; */
  /* border-radius: 30upx; */
}

.uni-searchbar__box {
  justify-content: flex-start !important;
}

.shares {
  position: absolute;
  width: 100upx;
  height: 120upx;
  bottom: 280upx;
  right: 32upx;
  opacity: 0;

}
</style>
